package com.example.demo.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author
 * @Description
 */
public class ClassUtil {
    public static Object invoke(Object object, String methodName, Object... args) {

//        ApplicationContext object = new ClassPathXmlApplicationContext("");
//        args = new Class[]{Class.forName("com.example.demo.service.UserService")};
//        methodName = "getBean";

        List<Class> argumentTypes = new ArrayList<>();
        if (args != null) {
            for (Object arg : args) {
                if (arg == null) {
                    argumentTypes.add(null);
                } else {
                    argumentTypes.add(arg.getClass());
                }
            }
        }
        Method method;
        try {
            if (!argumentTypes.isEmpty()) {
                method = object.getClass().getMethod(methodName, argumentTypes.toArray(new Class[0]));
            } else {
                method = object.getClass().getMethod(methodName);
            }
            return method.invoke(object, args);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
